<?php

namespace catchAdmin\phone\controller;

use catchAdmin\model\NeedMatchUser;
use catchAdmin\model\WechatUserPayment;
use catcher\base\CatchController;
use think\facade\Db;

class Notify extends CatchController

{

    /**
     * 充值回调
     */
    public function rechargeBalance()
    {
        $xml = file_get_contents('php://input');
        if (empty($xml)) {
            exit(returnXml('FAIL', 'php://input'));
        }
        $param = xmlToArray($xml);

        saveAccessLog($param);

//        $str = '{"appid":"wxbe6d52d49560cc65","bank_type":"CCB_DEBIT","cash_fee":"4","fee_type":"CNY","is_subscribe":"N","mch_id":"1723935252","nonce_str":"689155a14ba36","openid":"oCVtHvjfO6O3ea_yCee14O8k1L_I","out_trade_no":"17543551056666","result_code":"SUCCESS","return_code":"SUCCESS","sign":"03E14DA19A9AA4375AC0E74429FA8C2E","time_end":"20250805085150","total_fee":"4","trade_type":"JSAPI","transaction_id":"4200002825202508055554676473"}';
//        $param = json_decode($str, true);

        // 3. 验证基本参数
        if ($param['result_code'] != 'SUCCESS'
            || $param['return_code'] != 'SUCCESS') {
            exit(returnXml('FAIL', '验证基本参数'));
        }

        Db::startTrans();

        // 1.支付表
        {
            $WechatUserPayment_app = (new WechatUserPayment());

            $payment_msg = $WechatUserPayment_app
                ->where('app_id', $param['appid'])
                ->where('mch_id', $param['mch_id'])
                ->where('openid', $param['openid'])
                ->where('out_trade_no', $param['out_trade_no'])
                ->where('total_fee', mathChu($param['total_fee'], 100))
                ->where('pay_time', 0)
                ->find();

            if (empty($payment_msg)) {
                exit(returnXml('FAIL', '支付表 不存在'));
            }

            try {
                $payment_msg = $WechatUserPayment_app->saveDataCC([
                    'id'         => $payment_msg['id'],
                    'pay_result' => json_encode($param),
                    'pay_code'   => 1,
                    'pay_time'   => time(),
                ]);
            } catch (\Exception $e) {
                exit(returnXml('FAIL', '支付表 保存失败'));
            }
        }

        // 2.充值表
        {
            $WechatUserBalance_app = (new \catchAdmin\model\WechatUserBalance());

            // 101=充值
            if ($payment_msg['total_fee'] > 0) {
                try {
                    $WechatUserBalance_app->saveWechatUserBalance([
                        'wechat_user_id'         => $payment_msg['wechat_user_id'],
                        'balance_type'           => $payment_msg['balance_type'],
                        'balance_type_2'         => $payment_msg['balance_type_2'],
                        'num'                    => $payment_msg['total_fee'],
                        'out_trade_no'           => $payment_msg['out_trade_no'],
                        'wechat_user_payment_id' => $payment_msg['id'],
                    ]);
                } catch (\Exception $e) {
                    exit(returnXml('FAIL', '101=充值'));
                }

                // 充值有且公有一条成功充值记录
                if ($WechatUserBalance_app
                        ->where('wechat_user_payment_id', $payment_msg['id'])
                        ->where('balance_type_2', $payment_msg['balance_type_2'])
                        ->count() != 1) {
                    exit(returnXml('FAIL', '101=充值 充值有且公有一条成功充值记录'));
                }
            }

            // 201=赠积分
            if ($payment_msg['total_fee'] > 0) {
                try {
                    $WechatUserBalance_app->saveWechatUserBalance([
                        'wechat_user_id'         => $payment_msg['wechat_user_id'],
                        'balance_type'           => 2,
                        'balance_type_2'         => 201,

                        // haofuheng
                        'num'                    => $payment_msg['total_fee'] * 100,
                        'out_trade_no'           => $payment_msg['out_trade_no'],
                        'wechat_user_payment_id' => $payment_msg['id'],
                    ]);
                } catch (\Exception $e) {
                    exit(returnXml('FAIL', '201=赠积分'));
                }

                // 充值有且公有一条成功充值记录
                if ($WechatUserBalance_app
                        ->where('wechat_user_payment_id', $payment_msg['id'])
                        ->where('balance_type_2', 201)
                        ->count() != 1) {
                    exit(returnXml('FAIL', '201=赠积分 充值有且公有一条成功充值记录'));
                }
            }

            // 102=充值赠送
            if ($payment_msg['zeng_value'] > 0) {
                try {
                    $WechatUserBalance_app->saveWechatUserBalance([
                        'wechat_user_id'         => $payment_msg['wechat_user_id'],
                        'balance_type'           => $payment_msg['balance_type'],
                        'balance_type_2'         => 102,
                        'num'                    => $payment_msg['zeng_value'],
                        'out_trade_no'           => $payment_msg['out_trade_no'],
                        'wechat_user_payment_id' => $payment_msg['id'],
                    ]);
                } catch (\Exception $e) {
                    exit(returnXml('FAIL', '102=充值赠送'));
                }

                // 充值有且公有一条成功充值赠送记录
                if ($WechatUserBalance_app
                        ->where('wechat_user_payment_id', $payment_msg['id'])
                        ->where('balance_type_2', 102)
                        ->count() != 1) {
                    exit(returnXml('FAIL', '102=充值赠送 充值有且公有一条成功充值赠送记录'));
                }
            }
        }

        Db::commit();

        exit(returnXml('SUCCESS', 'OK'));
    }


    /**
     * 需求支付回调
     */
    public function needPay()
    {
        $xml = file_get_contents('php://input');
        if (empty($xml)) {
            exit(returnXml('FAIL', 'php://input'));
        }
        $param = xmlToArray($xml);

        saveAccessLog($param);

//        $str = '{"appid":"wxbe6d52d49560cc65","bank_type":"CCB_DEBIT","cash_fee":"5","fee_type":"CNY","is_subscribe":"N","mch_id":"1723935252","nonce_str":"68bce04475061","openid":"oCVtHvjfO6O3ea_yCee14O8k1L_I","out_trade_no":"17572086446824","result_code":"SUCCESS","return_code":"SUCCESS","sign":"60EF4F65111F99749B1D9ACE53401044","time_end":"20250907093114","total_fee":"5","trade_type":"JSAPI","transaction_id":"4200002542202509071685906854"}';
//        $param = json_decode($str, true);

        // 3. 验证基本参数
        if ($param['result_code'] != 'SUCCESS'
            || $param['return_code'] != 'SUCCESS') {
            exit(returnXml('FAIL', '验证基本参数'));
        }

        Db::startTrans();

        // 1.支付表
        {
            $WechatUserPayment_app = (new WechatUserPayment());

            $payment_msg = $WechatUserPayment_app
                ->where('app_id', $param['appid'])
                ->where('mch_id', $param['mch_id'])
                ->where('openid', $param['openid'])
                ->where('out_trade_no', $param['out_trade_no'])
                ->where('total_fee', mathChu($param['total_fee'], 100))
                ->where('pay_time', 0)
                ->find();

            if (empty($payment_msg)) {
                exit(returnXml('FAIL', '支付表 不存在'));
            }

            try {
                $payment_msg = $WechatUserPayment_app->saveDataCC([
                    'id'         => $payment_msg['id'],
                    'pay_result' => json_encode($param),
                    'pay_code'   => 1,
                    'pay_time'   => time(),
                ]);
            } catch (\Exception $e) {
                exit(returnXml('FAIL', '支付表 保存异常'));
            }
        }

        // 2.需求表
        {
            $NeedMatchUser_app = (new NeedMatchUser());

            $need_match_user_msg = $NeedMatchUser_app
                ->where('wechat_user_payment_id', $payment_msg['id'])
                ->where('pay_amount', $payment_msg['total_fee'])
                ->where('pay_time', 0)
                ->find();

            if (empty($need_match_user_msg)) {
                exit(returnXml('FAIL', '需求表 不存在'));
            }

            try {
                $need_match_user_msg = $NeedMatchUser_app->saveDataCC([
                    'id'       => $need_match_user_msg['id'],
                    'pay_type' => 2,
                    'pay_time' => time(),
                    'status'   => 2,
                ]);
            } catch (\Exception $e) {
                exit(returnXml('FAIL', '需求表 保存异常'));
            }
        }

        Db::commit();

        exit(returnXml('SUCCESS', 'OK'));
    }

}
